import type { Router } from 'vue-router';
import { PageEnum } from '/@/enums/pageEnum';
import { removeTabChangeListener } from '/@/logics/mitt/routeChange';
import { useAppStore } from '/@/store/modules/app';
import { useMultipleTabStore } from '/@/store/modules/multipleTab';
import { usePermissionStore } from '/@/store/modules/permission';
import { useUserStore } from '/@/store/modules/user';

export function createStateGuard(router: Router) {
  router.afterEach((to) => {
    // Just enter the login page and clear the authentication information
    // 如果进来的路由是login 就将用户的权限和身份的用户态全部重置；因为访问login页面意味着用户想要重新登录
    if (to.path === PageEnum.BASE_LOGIN) {
      const tabStore = useMultipleTabStore();
      const userStore = useUserStore();
      const appStore = useAppStore();
      const permissionStore = usePermissionStore();
      // 上边四行取全局的用户状态 下边四行全部重置 
      appStore.resetAllState(); // 路由、localStorage、sessionStorage、缓存
      permissionStore.resetState();  // 权限状态
      tabStore.resetState(); // 打开的tab条
      userStore.resetState(); // 用户信息
      removeTabChangeListener();
    }
  });
}
